package com.eight.filter;

import com.alibaba.fastjson2.JSON;
import com.eight.util.JWTTool;
import com.eight.vo.ComResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 网关拦过滤器用来实现redis的续租与校验
 * @Author: Van.Planifolia
 * @CreateTime: 2023-02-23  20:48
 * @Version: 1.0
 */
@Component
public class MyGlobalFilter implements GlobalFilter {
    @Value("#{'${other.request.path}'.split(',')}")
    private String[] paths;
    /**
     * 推荐使用Resource注入，不过也可以使用Autowired
     */
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 这个方法是用来拦截到每个请求，然后拿到用户的token进行判断若tk验证成功，并且雷迪斯中的key还在存活，就放行且刷新tk存活时间
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 若为登录我们就直接放行比较好
        String path = request.getPath().toString();
        System.out.println(path);
        // 已经过时的判断方法
//        if (path.startsWith("/login")) {
//            return chain.filter(exchange);
//        } else if (path.startsWith("/coupon/upload")) {
//            return chain.filter(exchange);
//        } else if (path.startsWith("/system/api/admin/imgUpload")) {
//            return chain.filter(exchange);
//        }else if(path.startsWith("/rent/carbrand/upload/")){
//            return chain.filter(exchange);
//        }

        // 并行流来处理放行断言
        if (Arrays.stream(paths).parallel().anyMatch(path::contains)){
            return chain.filter(exchange);
        }

            // 若不是我们就要开始验证tk了
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.hasText(token) && JWTTool.verifyToken(token) && Boolean.TRUE.equals(redisTemplate.hasKey(token))) {
            // 成功就刷新时间，filter继续往下走
            redisTemplate.expire(token, 30, TimeUnit.DAYS);
            return chain.filter(exchange);
        }
        // 若没通过就往前端推送错误
        ComResult result = new ComResult(5001, "登录失效ft");
        //3.3作JSON转换
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);

        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }
}
